﻿using DBUtility;
using Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using UtilityHelper;

namespace IYAKASAPortal.PrintAll
{
    class AutoPrintQue
    {
        public Queue<int> Queue_1;
        public Queue<int> Queue_U_1;

        private Dictionary<int, Queue<int>> dic_Queue = null;
        private Dictionary<int, Queue<int>> dic_U_Queue = null;
        private static object m_Lock = new object();
        public static volatile AutoPrintQue instance = null;
        private static List<int> PrintList = new List<int>();

        public static AutoPrintQue GetInstance()
        {
            lock (m_Lock)
            {
                if (instance == null)
                {
                    instance = new AutoPrintQue();
                    instance.Queue_1 = new Queue<int>();
                    instance.Queue_U_1 = new Queue<int>();
                    instance.dic_Queue = new Dictionary<int, Queue<int>>();
                    instance.dic_U_Queue = new Dictionary<int, Queue<int>>();

                    for (int i = 1; i < 8; i++)
                    {
                        instance.dic_Queue.Add(i, new Queue<int>());
                        instance.dic_U_Queue.Add(i, new Queue<int>());
                    }

                    instance.Start_Insert_PrintQue();
                }

                return instance;
            }
        }

        private void Start_Insert_PrintQue()
        {
            Thread _GetPrintQueue = new Thread(() =>
            {
                while (true)
                {
                    this.OfflineVehicle();
                    Thread.Sleep(3000);
                }
            });
            _GetPrintQueue.Start();
        }

        public int Get_Queue(int lineNum)
        {
            lock (m_Lock)
            {
                int i = 0;
                if (dic_Queue[lineNum].Count > 0)
                {
                    i = dic_Queue[lineNum].Dequeue();
                }
                return i;
            }
        }

        public void Clear_AutoPrintQue()
        {
            instance = null;
        }

        public int Get_U_Queue(int lineNum)
        {
            lock (m_Lock)
            {
                int i = 0;
                if (dic_U_Queue[lineNum].Count > 0)
                {
                    i = dic_U_Queue[lineNum].Dequeue();
                }
                return i;
            }
        }





        /// <summary>
        /// 记录日志
        /// </summary>
        /// <param name="JCLSH">检测流水线号</param>
        /// <param name="logMsg">日志消息</param>
        /// <param name="operatorName">操作员名称</param>
        /// <param name="type">日志类型</param>
        /// <param name="funName">方法名称</param>
        private void WriteLog(string JCLSH, string logMsg, string operatorName, LogHelper.LogType type, string funName)
        {
            try
            {
                #region 日志记录
                LogHelper logHelper = LogHelper.GetSingleLogHelper();
                string strCategory = LogHelper.LogType.Normal.ToString();
                LOG_INFO logInfo = new LOG_INFO();
                logInfo.Category = strCategory;
                logInfo.HostName = System.Net.Dns.GetHostName();
                logInfo.IPAddress = System.Net.Dns.GetHostAddresses(logInfo.HostName).GetValue(1).ToString();
                logInfo.LogTime = DateTime.Now;

                logInfo.JCLSH = JCLSH;
                logInfo.Log_Infor = logMsg;
                logInfo.OpName = operatorName;
                logInfo.Name = logHelper.GetLogName(type);
                logInfo.FunName = funName;

                logHelper.WriteLog(logInfo);
                #endregion
            }
            catch (Exception ex)
            {
                
            }
        }

        private string PrintAJ()
        {
            /*
             组装SQL步骤：
             * 1、直接组装总判定里勾选的条件，数据库字段里取出来的值为"1,2,3"时，则直接将 Z_PD=1 OR Z_PD = 2 OR Z_PD = 3 
             * 拼装到StringBuilder里备用。
             * 2、如果AJ_ZPDZT=1，则把（1）中组装好的sql拼入最终结果
             * 3、如果AJ_SHZPT=1,则把 " AND IsAudit = {数据库中AJ_SH的值}" 加入到结果里
             * 4、完成拼装就直接return出去，return之前把StringBuilder进行ToString();
             */
            string _strResult = string.Empty;
            StringBuilder _sbZPDSQL = new StringBuilder();
            _sbZPDSQL.Append("(");
            string[] _subConditon = PrintConfig.SelectValue("AJ_ZPD").Split(new char[] { ',' });
            for (int i = 0; i < _subConditon.Length; i++)
            {
                if (_subConditon[i] != "")
                {
                    _sbZPDSQL.Append("Z_PD=" + _subConditon[i]);
                    if (i < _subConditon.Length - 2)
                    {
                        _sbZPDSQL.Append(" OR ");
                    }
                }
            }
            _sbZPDSQL.Append(")");
            if (PrintConfig.SelectValue("AJ_ZPDZT") == "1" && PrintConfig.SelectValue("AJ_SHZT") == "1")
            {
                _strResult += _sbZPDSQL.ToString();
                _strResult += string.Format(" AND IsAudit={0} ", PrintConfig.SelectValue("AJ_SH"));
                return _strResult;
            }
            else if (PrintConfig.SelectValue("AJ_ZPDZT") == "1" && PrintConfig.SelectValue("AJ_SHZT") == "0")
            {
                return _sbZPDSQL.ToString();
            }
            else if (PrintConfig.SelectValue("AJ_ZPDZT") == "0" && PrintConfig.SelectValue("AJ_SHZT") == "1")
            {
                return _strResult += string.Format(" AND IsAudit={0} ", PrintConfig.SelectValue("AJ_SH"));
            }
            else return "1=1";

        }

        private void OfflineVehicle()
        {
            try
            {
                string strCondition = PrintAJ();
                string strSQL = string.Format("SELECT TOP 1 ID,Z_PD,JCXH,JYXM,JCLSH FROM RESULT_VEHICLE_INFO WHERE IsPrint=0  AND  JCLSH LIKE 'A%' AND {0}", strCondition);
                DataTable _dtTemp = new DataTable();
                DbHelper.GetTable(strSQL, ref _dtTemp);

                if (_dtTemp.Rows.Count > 0)
                {
                    DataRow _row = _dtTemp.Rows[0];
                    int _LineNum = int.Parse(_row["JCXH"].ToString());
                    int _ZPD = int.Parse(_row["Z_PD"].ToString());
                    int _ID = int.Parse(_row["ID"].ToString());

                    string strJYXM = Convert.ToString(_row["JYXM"]);
                    string strJCLSH = Convert.ToString(_row["JCLSH"]);
                    if (strJYXM != null && strJYXM.Contains("W1,") && strJCLSH != null)
                    {
                        try
                        {
                            Tools.UseTools useTolls = new Tools.UseTools();
                            useTolls.UploadZ1(strJCLSH);
                        }
                        catch(Exception ex)
                        {

                        }
   
                    }


                    string _sqlUpdateTable = string.Format("UPDATE RESULT_VEHICLE_INFO SET IsPrint = 1 WHERE ID = {0}", _ID);
                    WriteLog("", string.Format("查询到需要打印的数据{0},总判定:{1}", _ID, _ZPD), "", LogHelper.LogType.Normal, "自动打印");
                    if (DbHelper.ExecuteSql(_sqlUpdateTable))
                    {
                        WriteLog("", string.Format("更新了数据{0}的打印状态", _ID), "", LogHelper.LogType.Normal, "自动打印");

                        string strSearchSQL = string.Format("SELECT * FROM PRINT_RECORD WHERE DISPATCH_ID = {0}", _ID);
                        DataTable dt = new DataTable();
                        DbHelper.GetTable(strSearchSQL, ref dt);
                        if (dt.Rows.Count == 0)
                        {
                            string strUpdateSql = string.Format("INSERT INTO PRINT_RECORD (DISPATCH_ID) VALUES({0})", _ID);
                            DbHelper.ExecuteSql(strUpdateSql);
                            if (_ZPD == 1)
                            {
                                if (!dic_Queue[_LineNum].Contains(_ID))
                                    dic_Queue[_LineNum].Enqueue(_ID);
                            }
                            else
                            {
                                if (!dic_U_Queue[_LineNum].Contains(_ID))
                                {
                                    dic_U_Queue[_LineNum].Enqueue(_ID);
                                }
                            }
                        }

                    }
                }
            }
            catch (Exception ex)
            {
                WriteLog("error", ex.Message, "error", LogHelper.LogType.Error, "添加打印队列");
            }
        }      

    }
}
